package jp.sourceforge.akjrcp.videotools.subtitlemaker;



import java.io.File;
import java.io.IOException;
import java.util.List;

import jp.sourceforge.akjrcp.akj_betas.Akj_betasPlugin;
import jp.sourceforge.akjrcp.akj_betas.Messages;
import jp.sourceforge.akjrcp.commons.ui.FileDirChoicer;
import jp.sourceforge.akjrcp.commons.ui.AbstractFileDirChoicer.FileStatusChangeEvent;
import jp.sourceforge.akjrcp.commons.ui.AbstractFileDirChoicer.FileStatusChangeListener;
import jp.sourceforge.akjrcp.commons.ui.widget.LayoutBuilder;
import jp.sourceforge.akjrcp.commons.ui.widget.WidgetBuilder;
import jp.sourceforge.akjrcp.commons.util.ClipboardUtil;
import jp.sourceforge.akjrcp.commons.util.FileNameUtils;
import jp.sourceforge.akjrcp.ffmpeg.FFMpegFLVParser;
import jp.sourceforge.akjrcp.ffmpeg.FFMpegFileInfomation;
import jp.sourceforge.akjrcp.ffmpeg.FFMpegUI;
import jp.sourceforge.akjrcp.flvtools.explorer.ExplorerView.CustomFlowLayout;
import jp.sourceforge.akjrcp.subtitle.SubtitlePage;
import jp.sourceforge.akjrcp.subtitle.SubtitleUtils;
import jp.sourceforge.akjrcp.subtitle.srt.SRTList;
import jp.sourceforge.akjrcp.subtitle.srt.SRTObject;
import jp.sourceforge.akjrcp.subtitle.srt.SRTParser;
import jp.sourceforge.akjrcp.ui.draw2d.FileImageCache;
import jp.sourceforge.akjrcp.ui.param.ParamSpinnerAndScale;
import jp.sourceforge.akjrcp.ui.param.ParamTime;
import jp.sourceforge.akjrcp.util.TimeUtils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.FigureCanvas;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.StackLayout;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.part.ViewPart;

public class SubtitleMakerView  extends ViewPart {
		public static Log log=LogFactory.getLog(SubtitleMakerView.class);
		
		public static final String ID = SubtitleMakerView.class.getName();

		private FigureCanvas canvas;

		private SelectableFigureList childrenFiguresExplorer;

		private FileDirChoicer inputVideoFileChooser;

	

		private ParamSpinnerAndScale minVolumeScale;

		private ParamTime endTimeParam;

		private ParamTime startTimeParam;

		private Text subtitleText;

		private Figure[] selectionFigures=new Figure[0];
		
		private FileModifiedControler srtFileModifiedControler;
		
		private String lastSubtitle="";

		//private org.eclipse.swt.widgets.Label srtPath;
		private FileImageCache fileImageCache;

		private SimpleImageChecker imageChecker;

		private VideoThumbsCreater videoThumbs;

		private Figure rootFigure;

		private FileDirChoicer inputSrtFileChooser;
		@Override
		public void createPartControl(Composite parent) {
			this.getSite().getPage().addPartListener(new IPartListener(){

				@Override
				public void partActivated(IWorkbenchPart part) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void partBroughtToTop(IWorkbenchPart part) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void partClosed(IWorkbenchPart part) {
					cancelLoadVideo();
				}

				@Override
				public void partDeactivated(IWorkbenchPart part) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void partOpened(IWorkbenchPart part) {
					// TODO Auto-generated method stub
					
				}});
			fileImageCache=new FileImageCache();
			fileImageCache.setMaxSize(60*12);
			parent.setLayout(new GridLayout(1,false));
			
			Composite srtButtons=new Composite(parent,SWT.NULL);
			Composite two=new Composite(parent,SWT.NULL);
			two.setLayout(LayoutBuilder.makeGridLayoutNoMargin(2, false));
			two.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
			//millisec

			
			  /*
Group files=new Group(two,SWT.NULL);
			
				
			  files.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
			  files.setLayout(new GridLayout());
			  files.setText("files");
			  */
				  Composite fileButtons=new Composite(two,SWT.NULL);
				  fileButtons.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
				  fileButtons.setLayout(LayoutBuilder.makeGridLayoutNoMargin(4, false));
			  FileSelected selectedListener=new FileSelected();
				inputVideoFileChooser = new FileDirChoicer(fileButtons,SWT.BORDER,FileDirChoicer.FILE,Messages.getString("subtitlemaker.video"));
				inputVideoFileChooser.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
				inputVideoFileChooser.addFileListChangeListener(selectedListener);
				inputVideoFileChooser.setFilterExtensions(new String[]{"*.mp4;*.mpg;*.avi;*.flv;*.vob;*.wmv","*.mp4","*.mpg","*.avi","*.flv","*.vob","*.wmv"});
				inputVideoFileChooser.addFileListChangeListener(new FileStatusChangeListener(){

					@Override
					public void addList(FileStatusChangeEvent event) {
						openVideo(event.getFilePath());
					}

				

					@Override
					public void removeList(FileStatusChangeEvent event) {
						
					}});
				Button cancelVideo=new Button(fileButtons,SWT.NULL);
				cancelVideo.setText(Messages.getString("subtitlemaker.cancelLoad"));
				cancelVideo.addSelectionListener(new SelectionAdapter(){
					public void widgetSelected(SelectionEvent e) {
						cancelLoadVideo();
					}
				});
				
				  minVolumeScale=new ParamSpinnerAndScale(two,SWT.NULL,"min_volume",Messages.getString("subtitlemaker.millisec"));
					minVolumeScale.setMinimum(0);
					minVolumeScale.setMaximum(999);
					minVolumeScale.setValue(""+0);
					minVolumeScale.getSpinnerAndScale().getSpinner().setPageIncrement(10);
					
					
					//srt
				
				
				
				srtButtons.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
				srtButtons.setLayout(LayoutBuilder.makeGridLayoutNoMargin(4, false));
				
				
				inputSrtFileChooser = new FileDirChoicer(srtButtons,SWT.BORDER,FileDirChoicer.FILE,Messages.getString("subtitlemaker.srt"),true);
				inputSrtFileChooser.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
				inputSrtFileChooser.addFileListChangeListener(selectedListener);
				inputSrtFileChooser.setFilterExtensions(new String[]{"*.srt"});
				inputSrtFileChooser.addFileListChangeListener(new FileStatusChangeListener(){

					@Override
					public void addList(FileStatusChangeEvent event) {
						loadSrt(event.getFilePath());
					}

				

					@Override
					public void removeList(FileStatusChangeEvent event) {
						resetSrt();
					}});
				srtFileModifiedControler=new FileModifiedControler();
			
				/*
				srtPath = new org.eclipse.swt.widgets.Label (srtButtons,SWT.NULL);
				srtPath.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
				Button openSrt=new Button(srtButtons,SWT.NULL);
				openSrt.setText(Messages.getString("subtitlemaker.load_srt"));
				openSrt.addSelectionListener(new SelectionAdapter(){
					public void widgetSelected(SelectionEvent e) {
						openSrt();
					}
				});
				*/
				
				Button saveSrt=new Button(srtButtons,SWT.NULL);
				saveSrt.setText(Messages.getString("subtitlemaker.save_srt"));
				saveSrt.addSelectionListener(new SelectionAdapter(){
					public void widgetSelected(SelectionEvent e) {
						saveSrt();
					}
				});
				saveSrt.setEnabled(false);
				
				srtFileModifiedControler.addControl(saveSrt);
				Button saveasSrt=new Button(srtButtons,SWT.NULL);
				saveasSrt.setText(Messages.getString("subtitlemaker.saveas_srt"));
				saveasSrt.addSelectionListener(new SelectionAdapter(){
					public void widgetSelected(SelectionEvent e) {
						saveAsSrt();
					}
				});
				
				srtFileModifiedControler.addControl(saveSrt);
				Button reloadSrt=new Button(srtButtons,SWT.NULL);
				reloadSrt.setText(Messages.getString("subtitlemaker.reload"));
				reloadSrt.addSelectionListener(new SelectionAdapter(){
					public void widgetSelected(SelectionEvent e) {
						loadSrt(srtFileModifiedControler.getFilePath());
					}
				});
			  
			  Composite edits=new Composite(parent,SWT.NULL);
			  
			  edits.setLayout(LayoutBuilder.makeGridLayoutNoMargin(4, false));
			  Composite times=WidgetBuilder.createTwoGridLayoutComposite(edits, SWT.NULL);
			  startTimeParam = new ParamTime(times,SWT.NULL,"time",Messages.getString("subtitlemaker.startTime"),false,true,true,false);
			  startTimeParam.setEnabled(false);
			  endTimeParam = new ParamTime(times,SWT.NULL,"time",Messages.getString("subtitlemaker.endTime"),false,true,true,false);
			  endTimeParam.setEnabled(false);
			  
			  subtitleText = new Text(edits,SWT.MULTI);
				GridData textData=new GridData();//for vista//TODO still here is problem
				  textData.heightHint=40;
				  textData.grabExcessVerticalSpace=true;
				  textData.widthHint=400;
				  subtitleText.setLayoutData(textData);
				  
			  Composite buttons=WidgetBuilder.createTwoGridLayoutComposite(edits, SWT.NULL);
			  Button update=new Button(buttons,SWT.NULL);
			  update.setText(Messages.getString("subtitlemaker.update"));
			  update.addSelectionListener(new SelectionListener(){

				@Override
				public void widgetDefaultSelected(SelectionEvent e) {
					
				}

				@Override
				public void widgetSelected(SelectionEvent e) {
					updateData();
				}});
			
			
			  //timeParam.setValue(TimeUtils.toTimeText(time));
			 //Composite controls=new Composite(parent,SWT.NULL);
			 //main
			    
			  GridData data=new GridData();//for vista//TODO still here is problem
			    data.heightHint=400;
			    data.grabExcessVerticalSpace=true;
			    data.widthHint=680;
			    
			    data.grabExcessHorizontalSpace=true;
			    
			  canvas = new FigureCanvas(parent);
				//canvas.setLayoutData(GridData.FILL_BOTH);
				canvas.setLayoutData(new GridData(GridData.FILL_BOTH));
			    
			    rootFigure = new Figure();
				rootFigure.setLayoutManager(new StackLayout());
				canvas.setContents(rootFigure);
				canvas.addKeyListener(new KeyListener(){

					public void keyPressed(KeyEvent e) {
						
					}

					public void keyReleased(KeyEvent e) {
						
						if(e.stateMask == SWT.CTRL && e.keyCode==97){
							childrenFiguresExplorer.selectAll();
						}
					}
					
				});
				
				
				createPopupMenu(canvas);
				
				
			
			
		}
		
		private void createPopupMenu(Control control){
			Menu canvasPopup = new Menu(control);
			canvas.setMenu(canvasPopup);
			MenuItem selectAll = new MenuItem(canvasPopup, SWT.PUSH);
			selectAll.setText(Messages.getString("explorer.select_all"));
			selectAll.addSelectionListener(new SelectionListener() {

				public void widgetSelected(SelectionEvent e) {
					childrenFiguresExplorer.selectAll();
				}

				public void widgetDefaultSelected(SelectionEvent e) {
					// TODO Auto-generated method stub

				}

			});
			
			MenuItem copyTime = new MenuItem(canvasPopup, SWT.PUSH);
			copyTime.setText(Messages.getString("explorer.copy_time"));
			copyTime.addSelectionListener(new SelectionListener() {

				public void widgetSelected(SelectionEvent e) {
					Figure[] fs=childrenFiguresExplorer.getSelectionFigures();
					if(fs.length>0){
						long time=(Long) ((ThumbnailFigure)fs[0]).getData();
						String label=TimeUtils.toTimeText(time,true,true,true,false);
						ClipboardUtil.setClipboard(getSite().getShell().getDisplay(), label);
					}
				}

				public void widgetDefaultSelected(SelectionEvent e) {
					// TODO Auto-generated method stub

				}

			});
			
			MenuItem copyTime2 = new MenuItem(canvasPopup, SWT.PUSH);
			copyTime2.setText(Messages.getString("explorer.copy_duration_time"));
			copyTime2.addSelectionListener(new SelectionListener() {

				public void widgetSelected(SelectionEvent e) {
					Figure[] fs=childrenFiguresExplorer.getSelectionFigures();
					if(fs.length>0){
						long time=(Long) ((ThumbnailFigure)fs[0]).getData();
						long time2=(Long) ((ThumbnailFigure)fs[fs.length-1]).getData();
						String label=TimeUtils.toTimeText(time2-time,true,true,true,false);
						ClipboardUtil.setClipboard(getSite().getShell().getDisplay(), label);
					}
				}

				public void widgetDefaultSelected(SelectionEvent e) {
					// TODO Auto-generated method stub

				}

			});
		}
		
		//for multi load,otherwise bug
		private void createNewFiguresExplorer(){
			rootFigure.removeAll();
			childrenFiguresExplorer = new SelectableFigureList();
			childrenFiguresExplorer.setBackgroundColor(ColorConstants.white);
			childrenFiguresExplorer.setLayoutManager(new CustomFlowLayout(canvas,rootFigure));
			rootFigure.add(childrenFiguresExplorer);
			childrenFiguresExplorer.addSelectionChangeListener(new SelectionChangeListener(){

				@Override
				public void selectionChanged(SelectableFigureList parent,
						Figure[] oldSelections, Figure[] newSelections) {
					newSelections(newSelections);
				}});
		}

		protected void openVideo(String path){
			loadVideo(path);
			resetSrt();
			//load srt if exist
			if(srtFileModifiedControler.getFilePath()==null || srtFileModifiedControler.getFilePath().equals("")){
				String srtPath=FileNameUtils.getChangedExtensionName(path, "srt");
				if(new File(srtPath).exists()){
					loadSrt(srtPath);
				}
			}			
		}
		private void clearSrtData(){
			
			startTimeParam.setValue("00:00:00.000");
			endTimeParam.setValue("00:00:00.000");
			minVolumeScale.setValue(""+0);
			subtitleText.setText("");
			
			List flists=childrenFiguresExplorer.getChildren();
			for (int i = 0; i < flists.size(); i++) {
				ThumbnailFigure figure=(ThumbnailFigure)flists.get(i);
				figure.setLabel("");//clear
				setFigureTime(figure,i*1000);
			}
		}
		private void resetSrt() {
			inputSrtFileChooser.setFilePath(null);
			srtFileModifiedControler.setFilePath(null);
			srtFileModifiedControler.setModified(false);
			srtFileModifiedControler.setEncoding(null);
			clearSrtData();
		}

		protected void loadSrt(String srtPath) {
			clearSrtData();
			List flists=childrenFiguresExplorer.getChildren();
			inputSrtFileChooser.setFilePath(srtPath);
			srtFileModifiedControler.setFilePath(srtPath);
			SRTParser parser=new SRTParser();
			try {
				SRTList list=null;
			
					list = SubtitleUtils.loadSrt(new File(srtPath), "MS932");
					srtFileModifiedControler.setEncoding(list.getEncoding());
				list.sort();
				//log.info(list);
				for(int i=0;i<list.size();i++){
					long start=list.getSRTObjectAt(i).getStart().getTime();
					long end=list.getSRTObjectAt(i).getEnd().getTime();
					int startIndex=(int) (start/1000);
					int endIndex=(int) (end/1000);
					if(end%1000>0){
						endIndex++;
					}else{
						end-=1000;
					}
					log.trace("sindex="+startIndex+",eIndex="+endIndex);
					for(int j=startIndex;j<endIndex;j++){
						if(j>=0 && j<flists.size()){
							ThumbnailFigure figure=(ThumbnailFigure)flists.get(j);
							figure.setLabel(list.getSRTObjectAt(i).getText());
							log.trace(j+","+list.getSRTObjectAt(i).getText());
							if(j==startIndex){
								setFigureTime(figure,start);
							}else if(j==endIndex-1){
								setFigureTime(figure,end);
							}
						}
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			lastSubtitle=toSubtitle().toString();
			srtFileModifiedControler.setModified(false);
		}

		protected void saveAsSrt() {
			FileDialog fileDialog=new FileDialog(getSite().getShell(),SWT.SAVE);
			fileDialog.setFilterExtensions(new String[]{"*.srt"});
			
			
			if(!inputVideoFileChooser.getAbsoluteFilePath().equals("")){
				File videoFile=new File(inputVideoFileChooser.getAbsoluteFilePath());
				if(videoFile!=null){
					File srt=new File(FileNameUtils.getChangedExtensionName(videoFile, "srt", true));
					if(!srt.exists()){
						fileDialog.setFileName(srt.getAbsolutePath());
					}else{
						fileDialog.setFilterPath(srt.getParent());
					}
					}
			}
			
			String path=fileDialog.open();
			if(path!=null){
				srtFileModifiedControler.setFilePath(path);
				//srtPath.setText(path);
				inputSrtFileChooser.setFilePath(path);
				writeSrt();
			}
		}

		protected void saveSrt() {
			if(srtFileModifiedControler.getFilePath()==null){
				saveAsSrt();
				return;
			}
			writeSrt();
		}
		protected void writeSrt(){
			if(srtFileModifiedControler.getFilePath()==null){
				return;
			}
			SRTList srt=toSubtitle();
			try {
				
				FileUtils.writeStringToFile( new File(srtFileModifiedControler.getFilePath()), srt.toString(), getSrtEncoding());
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			srtFileModifiedControler.setModified(false);
		}
		
		private String getSrtEncoding(){
			String encoding=srtFileModifiedControler.getEncoding();
			if(encoding==null){
				encoding=Akj_betasPlugin.getDefault().getPreferenceStore().getString(SubtitlePage.DEFAULT_ENCODING);
				if(encoding.equals("")){
					encoding=SubtitlePage.ENCODING_MS932;
				}
			}else if(encoding.equals("")){
				encoding=SubtitlePage.ENCODING_MS932;
			}
			return encoding;
		}

		protected void openSrt() {
			FileDialog fileDialog=new FileDialog(getSite().getShell());
			fileDialog.setFilterExtensions(new String[]{"*.srt"});
			if(!inputVideoFileChooser.getAbsoluteFilePath().equals("")){
				//default same as video
				fileDialog.setFilterPath(new File(inputVideoFileChooser.getAbsoluteFilePath()).getParent());
			}
			
			String path=fileDialog.open();
			if(path!=null){
				loadSrt(path);
			}
		}

		protected void updateData() {
			for (int i = 0; i < selectionFigures.length; i++) {
				ThumbnailFigure figure=(ThumbnailFigure)selectionFigures[i];
				String text=subtitleText.getText();
				text=text.replace("\r\n", ""+((char)0));
				figure.setLabel(text);
				long time=(Long) figure.getData();
				//sync time.
				long start= (time/1000);
				long newTime=(long) (start*1000+Double.parseDouble(minVolumeScale.getValue()));
				setFigureTime(figure,newTime);
			}
			checkModified();
		}

		public void setFigureTime(ThumbnailFigure figure,long time){
			figure.setData(time);
			if(figure.getChildren().size()>2){
			Label l=(Label)figure.getChildren().get(2);
			String newLabel=TimeUtils.toTimeText(time, false, true, true, true);
			l.setText(newLabel);
			}
		}
		private void checkModified() {
			String newSrt=toSubtitle().toString();
			log.trace(newSrt);
			if(!newSrt.equals(lastSubtitle)){
				srtFileModifiedControler.setModified(true);
			}
		}
		
		private SRTList toSubtitle(){
			List list=childrenFiguresExplorer.getChildren();
			SRTList srtList=new SRTList();
			SRTObject lastObject=null;
			long lastTime=0;
			for(int i=0;i<list.size();i++){
				ThumbnailFigure figure=(ThumbnailFigure)list.get(i);
				long time=(Long) figure.getData();
				
				if(figure.getLabel().equals("")){
					if(lastObject!=null){
						long endTime=(Long) figure.getData();
						if(lastTime%1000!=0){
							endTime=lastTime;
							if(lastObject.getStart().getTime()==endTime){
								endTime=(Long) figure.getData();
							}
						}
						lastObject.setEndTime(endTime);
						srtList.add(lastObject);
						lastObject=null;
					}
				}else{
					if(lastObject==null){
						
						lastObject=new SRTObject();
						lastObject.setStartTime(time);
						lastObject.setText(figure.getLabel());
					}else{
						//continue
						if(!lastObject.getText().equals(figure.getLabel())){
							//end
							long endTime=(Long) figure.getData();
							if(lastTime%1000!=0){
								endTime=lastTime;
								if(lastObject.getStart().getTime()==endTime){
									endTime=(Long) figure.getData();
								}
							}
							lastObject.setEndTime(endTime);
							srtList.add(lastObject);
							//new
							lastObject=new SRTObject();
							lastObject.setStartTime(time);
							lastObject.setText(figure.getLabel());
						}
					}
				}
				lastTime=time;
			}
			if(lastObject!=null){//add last
				ThumbnailFigure figure=(ThumbnailFigure)list.get(list.size()-1);
				long endTime=(Long) figure.getData()+1000;
				lastObject.setEndTime(endTime);
				srtList.add(lastObject);
			}
			srtList.reindex();
			return srtList;
		}

		protected void loadText() {
			if(selectionFigures.length>0){
				ThumbnailFigure figure=(ThumbnailFigure)selectionFigures[0];
				String text=figure.getLabel();

				text=text.replace(""+(char)0,"\r\n");

				
				subtitleText.setText(text);
			}else{
				subtitleText.setText("");
			}
		}
		protected void loadTime() {
			if(selectionFigures.length>0){
				ThumbnailFigure figure=(ThumbnailFigure)selectionFigures[0];
			
				long time=(Long) figure.getData();
				//log.trace(time);
				int start=(int) (time/1000);
				int ms=(int) (time%1000);
				startTimeParam.setValue(TimeUtils.toTimeText(time));
				
				ThumbnailFigure figure2=(ThumbnailFigure)selectionFigures[selectionFigures.length-1];
				
				long time2=(Long) figure2.getData();
				endTimeParam.setValue(TimeUtils.toTimeText(time2+1000));
				minVolumeScale.setValue(""+ms);
			}else{
				startTimeParam.setValue("00:00:00.000");
				endTimeParam.setValue("00:00:00.000");
				minVolumeScale.setValue(""+0);
			}
		}
		private void newSelections(Figure[] newFigures){
			boolean doload=false;
			if(selectionFigures.length==0 || newFigures.length==1){
				doload=true;
			}
			//load data?
			selectionFigures=newFigures;
			if(doload){//only new item selected reload
			loadText();
			}
			loadTime();
			
		}
		public void loadVideo(String path){
			//inputVideoFileChooser.getAbsoluteFilePath()
			createThumbnails(path);
		}
		public void createThumbnails(String path){
			if(inputVideoFileChooser.getAbsoluteFilePath().equals("")){
				return;//
			}
			String ffmpeg=FFMpegUI.getFFmpegOrPureFFMpeg();
			if(ffmpeg==null){
				return;
			}
			FFMpegFileInfomation videoInfo=new FFMpegFLVParser(ffmpeg).parseFile(new File(path));
			String duration=videoInfo.getDuration();
			log.info(duration);
			long dms=TimeUtils.toMillisecond(duration);
			int index=(int) (dms/1000);
			if(dms%1000!=0){
				index++;
			}
			createNewFiguresExplorer();
			
			fileImageCache.removeAll();
			cancelLoadVideo();//stop pre load
			
			ThumbnailPreference preference=new ThumbnailPreference();
			preference.clearOldFiles();
			preference.setWidth(240);
			if(videoInfo.getAspectRatio()!=null && videoInfo.getAspectRatio().equals("16:9")){
				preference.setHeight(134);
			}else{
			preference.setHeight(180);
			}
			preference.setVideoPath(path);
			videoThumbs = new VideoThumbsCreater(preference);
			videoThumbs.start();
			
			
			childrenFiguresExplorer.removeAll();
			
			//pre create
			for(int i=0;i<index;i++){
				createThumbnailFigures(preference,i);
			}
			
			
			
			imageChecker = new SimpleImageChecker(preference,getSite().getShell(),childrenFiguresExplorer);
			
			videoThumbs.setImageChecker(imageChecker);
			imageChecker.start();
		}
		
		private void createThumbnailFigures(ThumbnailPreference preference,int index){
			 String numStr=FileNameUtils.digited(index+1,5);
			 String fileName=preference.getBaseName()+numStr+"."+preference.getExtension();
			 File file=new File(preference.getBaseDir(),fileName);
			 
			 long millisecond=index*1000;
			 
				ThumbnailFigure figure=new ThumbnailFigure(file.getAbsolutePath(),fileImageCache,preference.getWidth(),preference.getHeight());
				figure.setData(millisecond);
				
				String label=TimeUtils.toTimeText(millisecond, false, true, true, true);
				
				Label l=new Label(label);
				l.setOpaque(true);
				figure.add(l,new Rectangle(2,2,100,10));
				childrenFiguresExplorer.add(figure);
		}
		
		@Override
		public void setFocus() {
			
		}
		
		public class FileSelected implements FileStatusChangeListener{

			public void addList(FileStatusChangeEvent event) {
				
			
			}

			public void removeList(FileStatusChangeEvent event) {
			
			}
			
		}
		public void cancelLoadVideo(){
			if(videoThumbs!=null){
				if(videoThumbs.getExecuter()!=null){
					videoThumbs.getExecuter().cancel();
				}
			}
			
			//old one make problem
			if(imageChecker!=null){
				imageChecker.setCancelled(true);
				imageChecker=null;
			}
		}
}
